package com.aierkeji.b2c.utils;

import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class WebUtils extends org.springframework.web.util.WebUtils {

	@SuppressWarnings("unchecked")
	public static <V> V getParamsInMap(Map<String, Object> map, String key, Class<V> clazz) {
		if (map != null) {
			Object o = map.get(key);
			if (clazz.isInstance(o)) {
				return (V) o;
			}
		}
		return null;
	}

	public static Map<String, Object> getParamsMap(HttpServletRequest request) {
		Map<String, String[]> oMap = request.getParameterMap();
		Map<String, Object> result = new HashMap<>();
		for (String paramName : oMap.keySet()) {
			if (oMap.get(paramName) != null && oMap.get(paramName).length > 0) {
				result.put(paramName, oMap.get(paramName)[0]);
			}
		}
		return result;
	}

	public static String getParamsInMap(Map<String, String> map, String key) {
		if (map != null) {
			return map.get(key);
		}
		return null;
	}

	public static boolean checkParamsIsNull(Object... objs) {
		for (Object obj : objs) {
			if (obj == null) {
				return true;
			}
			if (obj instanceof String) {
				if (StringUtils.isBlank(obj.toString())) {
					return true;
				}
			}
			if (obj instanceof Collection) {
				if (CollectionUtils.isEmpty((Collection<?>) obj)) {
					return true;
				}
			}
		}

		return false;
	}

	public static String getIpAddress(HttpServletRequest request) {
		 String Xip = request.getHeader("X-Real-IP");
	        String XFor = request.getHeader("X-Forwarded-For");
	        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
	            //多次反向代理后会有多个ip值，第一个ip才是真实ip
	            int index = XFor.indexOf(",");
	            if(index != -1){
	                return XFor.substring(0,index);
	            }else{
	                return XFor;
	            }
	        }
	        XFor = Xip;
	        if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
	            return XFor;
	        }
	        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
	            XFor = request.getHeader("Proxy-Client-IP");
	        }
	        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
	            XFor = request.getHeader("WL-Proxy-Client-IP");
	        }
	        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
	            XFor = request.getHeader("HTTP_CLIENT_IP");
	        }
	        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
	            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
	        }
	        if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
	            XFor = request.getRemoteAddr();
	        }
		return XFor;
	}

}
